package com.example.yinhangmiaosha.realm;

import com.example.yinhangmiaosha.controller.OrderController;
import com.example.yinhangmiaosha.domain.User;
import com.example.yinhangmiaosha.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;

import java.util.List;

public class UserRealm extends AuthorizingRealm {

    private static final Logger LOGGER = LoggerFactory.getLogger(OrderController.class);

    @Autowired
    UserService userService;

    // 授权（用户权限不足将执行）
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        LOGGER.info("授权用户中...");
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.addStringPermission("user");
        return info;
    }

    // 认证（用户登录时将执行）
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        LOGGER.info("认证用户中...");
        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) token;
        String username = usernamePasswordToken.getUsername();
        usernamePasswordToken.getPassword();
        User user = userService.getUserByName(username);
        if(user == null) return null;
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user,
                user.getPassword(),"user");
        return info;
    }
}
